1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
/*!
Type annotations
*/
use super::*;

/// An owned type annotation
//TODO: "triangular" substitution
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Annotation(TermId);

impl Annotation {
    /// Create a new annotation given a base and a type
    pub fn new_unchecked(
        base: TermId,
        ty: TermId,
        ctx: &mut (impl ConsCtx + ?Sized),
    ) -> Annotation {
        let base = base.consed(ctx);
        if let Some(true) = base.is_subtype(&ty) {
            Annotation(base)
        } else {
            let ty = ty.consed(ctx);
            Annotation(Refl::new_unchecked(base, ty, ctx).into_id_with(ctx))
        }
    }

    /// Create a new, checked annotation given a base and a type
    pub fn new(
        base: TermId,
        ty: TermId,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Annotation, Error> {
        match base.eq_in(&ty, ctx.eq_ctx()) {
            Some(true) => Ok(Self::new_unchecked(base, ty, ctx.cons_ctx())),
            Some(false) => Err(Error::TypeMismatch),
            None => Err(Error::TermUnificationFailure),
        }
    }

    /// Try to create an annotation given a type
    pub fn from_ty(ty: TermId) -> Result<Annotation, Error> {
        if let Some(false) = ty.is_local_ty() {
            Err(Error::ExpectedType)
        } else {
            Ok(Annotation(ty))
        }
    }

    /// Try to create an annotation given a path
    pub fn from_path(p: TermId) -> Result<Annotation, Error> {
        if let Term::Refl(r) = &*p {
            if let Some(eq) = r.as_equal() {
                Self::from_ty(eq.clone())
            } else {
                match r.right().is_local_ty() {
                    Some(true) => {
                        debug_assert_ne!(r.left().is_local_ty(), Some(false));
                    }
                    Some(false) => {
                        debug_assert_ne!(r.left().is_local_ty(), Some(true));
                        return Err(Error::ExpectedType);
                    }
                    None => {
                        if let Some(false) = r.left().is_local_ty() {
                            return Err(Error::ExpectedType);
                        }
                    }
                }
                Ok(Annotation(p))
            }
        } else {
            Err(Error::ExpectedRefl)
        }
    }

    /// Try to create an annotation from an ID
    pub fn from_id(id: TermId) -> Result<Annotation, Error> {
        if let Term::Refl(_) = &*id {
            Self::from_ty(id)
        } else {
            Self::from_path(id)
        }
    }

    /// Convert this annotation into it's type
    pub fn into_ty(self) -> TermId {
        match &*self.0 {
            Term::Refl(path) => path.right().clone(),
            _ => self.0,
        }
    }

    /// Convert this annotation into it's base
    pub fn into_base(self) -> TermId {
        match &*self.0 {
            Term::Refl(path) => path.left().clone(),
            _ => self.0,
        }
    }

    /// Check whether this annotation is a sub-annotation of another
    pub fn is_sub_annot(&self, other: &Annotation) -> bool {
        self.ty().is_subtype(&*other.ty()).unwrap_or(false)
    }

    /// Attempt to coerce the type of this annotation in a given typing context.
    #[inline]
    pub fn coerced_ty(
        &self,
        target: &TermId,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Annotation, Error> {
        if let Some(coerced) = self.coerce_ty(target, ctx)? {
            Ok(coerced)
        } else {
            Ok(self.consed(ctx.cons_ctx()))
        }
    }
}

impl Cons for Annotation {
    type Consed = Annotation;

    #[inline]
    fn cons(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> Option<Self::Consed> {
        self.0.cons(ctx).map(Annotation)
    }

    #[inline]
    fn to_consed_ty(&self) -> Self::Consed {
        self.clone()
    }
}

impl Substitute for Annotation {
    type Substituted = Annotation;

    #[inline]
    fn subst_rec(
        &self,
        ctx: &mut (impl SubstCtx + ?Sized),
    ) -> Result<Option<Self::Substituted>, Error> {
        Ok(self.0.subst_rec(ctx)?.map(Annotation))
    }

    #[inline]
    fn from_consed(this: Self::Consed, _ctx: &mut (impl ConsCtx + ?Sized)) -> Self::Substituted {
        this
    }
}

impl HasDependencies for Annotation {
    #[inline]
    fn has_var_dep(&self, ix: u32, equiv: bool) -> bool {
        self.0.has_var_dep(ix, equiv)
    }

    #[inline]
    fn has_dep_below(&self, ix: u32, base: u32) -> bool {
        self.0.has_dep_below(ix, base)
    }

    #[inline]
    fn get_filter(&self) -> VarFilter {
        self.0.get_filter()
    }
}

impl Typecheck for Annotation {
    #[inline]
    fn do_local_tyck(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> bool {
        self.borrow_annot().do_local_tyck(ctx)
    }

    #[inline]
    fn do_global_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        self.borrow_annot().do_annot_tyck(ctx)
    }

    #[inline]
    fn do_annot_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        self.borrow_annot().do_annot_tyck(ctx)
    }

    #[inline]
    fn local_tyck(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> bool {
        self.borrow_annot().local_tyck(ctx)
    }

    #[inline]
    fn global_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        self.borrow_annot().global_tyck(ctx)
    }

    #[inline]
    fn annot_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        self.borrow_annot().annot_tyck(ctx)
    }

    #[inline]
    fn tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        self.borrow_annot().tyck(ctx)
    }

    #[inline]
    fn load_flags(&self) -> TyckFlags {
        self.borrow_annot().load_flags()
    }

    #[inline]
    fn set_flags(&self, flags: TyckFlags) {
        self.borrow_annot().set_flags(flags)
    }

    #[inline]
    fn tyck_var(&self, ctx: &mut (impl TyCtxMut + ConsCtx + ?Sized)) -> Option<bool> {
        self.borrow_annot().tyck_var(ctx)
    }

    #[inline]
    fn maybe_tyck(&self) -> bool {
        self.borrow_annot().maybe_tyck()
    }
}

impl TermEq for Annotation {
    #[inline]
    fn eq_in(&self, other: &Self, ctx: &mut (impl TermEqCtxMut + ?Sized)) -> Option<bool> {
        if !ctx.cmp_annot() {
            Some(true)
        } else if ctx.is_struct() {
            self.0.eq_in(&other.0, ctx)
        } else {
            //TODO: generalize for non-tracing compare...
            self.ty().eq_in(&*other.ty(), ctx)
        }
    }
}

/// A borrowed type annotation
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum AnnotationRef<'a> {
    /// A type annotation consisting of a base type and an equal surface type
    Path(&'a Refl),
    /// A simple type annotation
    Type(&'a TermId),
    /// A type annotation where the type is guaranteed to be a typing universe
    Universe(Universe),
}

/// Return the same expression for every variant of `Annotation`
#[macro_export]
macro_rules! for_annot_ref {
    ($t:expr; $i:ident => $e:expr $(,$p:pat => $r:expr)*) => {
        {
            #[allow(unreachable_patterns)]
            match $t {
                $($p => $r,)*
                $crate::term::annot::AnnotationRef::Path($i) => $e,
                $crate::term::annot::AnnotationRef::Type($i) => $e,
                $crate::term::annot::AnnotationRef::Universe($i) => $e,
            }
        }
    };
}

impl<'a> AnnotationRef<'a> {
    /// Get this annotation as a universe, if possible
    pub fn as_universe(&self) -> Option<Universe> {
        match self {
            AnnotationRef::Universe(u) => Some(u.clone()),
            AnnotationRef::Type(ty) => match &***ty {
                Term::Universe(u) => Some(u.as_universe().clone()),
                _ => None,
            },
            AnnotationRef::Path(p) => p.as_universe(),
        }
    }

    /// Get this annotation as a dependent function type, if possible
    pub fn as_pi(&self) -> Option<&'a Pi> {
        match self {
            AnnotationRef::Universe(_) => None,
            AnnotationRef::Type(ty) => match &***ty {
                Term::Pi(p) => Some(p),
                _ => None,
            },
            AnnotationRef::Path(p) => p.as_pi(),
        }
    }

    /// Get the type of this annotation with a given context. Note borrowed values may not be consed.
    pub fn get_ty_id(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> Cow<'a, TermId> {
        match self {
            AnnotationRef::Type(ty) => Cow::Borrowed(ty),
            AnnotationRef::Path(p) => Cow::Borrowed(p.right()),
            AnnotationRef::Universe(u) => Cow::Owned(u.clone_into_id_with(ctx)),
        }
    }

    /// Get the base type of this annotation with a given context
    pub fn get_base_id(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> Cow<'a, TermId> {
        match self {
            AnnotationRef::Type(ty) => Cow::Borrowed(ty),
            AnnotationRef::Path(p) => Cow::Borrowed(p.left()),
            AnnotationRef::Universe(u) => Cow::Owned(u.clone_into_id_with(ctx)),
        }
    }

    /// Get the type of this annotation
    #[inline]
    pub fn get_ty(&self) -> Cow<'a, Term> {
        match self {
            AnnotationRef::Universe(u) => Cow::Owned(Term::Universe(u.clone().into())),
            AnnotationRef::Type(t) => Cow::Borrowed(t),
            AnnotationRef::Path(p) => Cow::Borrowed(p.right()),
        }
    }

    /// Get the transported type of this annotation, if any
    #[inline]
    pub fn get_diff_ty(&self) -> Option<&'a TermId> {
        match self {
            AnnotationRef::Universe(_) => None,
            AnnotationRef::Type(_) => None,
            AnnotationRef::Path(p) => p.diff_right(),
        }
    }

    /// Get the base type of this annotation
    #[inline]
    pub fn get_base(&self) -> Cow<'a, Term> {
        match self {
            AnnotationRef::Universe(u) => Cow::Owned(Term::Universe(u.clone().into())),
            AnnotationRef::Type(t) => Cow::Borrowed(t),
            AnnotationRef::Path(p) => Cow::Borrowed(p.left()),
        }
    }

    /// Attempt to coerce the type of this annotation in a given typing context.
    #[inline]
    pub fn get_coerce_ty(
        &self,
        target: &TermId,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Option<Annotation>, Error> {
        match self {
            AnnotationRef::Universe(u) => u.coerce_annot_ty(target, ctx),
            AnnotationRef::Type(t) => t.coerce_annot_ty(target, ctx),
            AnnotationRef::Path(p) => p.coerce_right(target, ctx),
        }
    }
}

impl HasDependencies for AnnotationRef<'_> {
    fn has_var_dep(&self, ix: u32, equiv: bool) -> bool {
        for_annot_ref!(self; t => t.has_var_dep(ix, equiv))
    }

    fn has_dep_below(&self, ix: u32, base: u32) -> bool {
        for_annot_ref!(self; t => t.has_dep_below(ix, base))
    }

    #[inline]
    fn get_filter(&self) -> VarFilter {
        for_annot_ref!(self; t => t.get_filter())
    }
}

impl Typecheck for AnnotationRef<'_> {
    fn do_local_tyck(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> bool {
        for_annot_ref!(self; t => t.do_local_tyck(ctx))
    }

    fn do_global_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        //TODO: check refl sides are types?
        for_annot_ref!(self; t => t.do_global_tyck(ctx))
    }

    fn do_annot_tyck(&self, ctx: &mut (impl TyCtxMut + ?Sized)) -> Option<bool> {
        for_annot_ref!(self; t => t.do_annot_tyck(ctx))
    }

    #[inline]
    fn load_flags(&self) -> TyckFlags {
        for_annot_ref!(self; t => t.load_flags())
    }

    #[inline]
    fn set_flags(&self, flags: TyckFlags) {
        for_annot_ref!(self; t => t.set_flags(flags))
    }
}

/// A term which behaves like a (potentially borrowed) annotation
pub trait AnnotationLike {
    /// Borrow this term's underlying annotation
    fn borrow_annot(&self) -> AnnotationRef;

    /// Get the type of this annotation
    #[inline]
    fn ty(&self) -> Cow<Term> {
        self.borrow_annot().get_ty()
    }

    /// Get the transported type of this annotation, if any
    #[inline]
    fn diff_ty(&self) -> Option<&TermId> {
        self.borrow_annot().get_diff_ty()
    }

    /// Get the base type of this annotation
    #[inline]
    fn base(&self) -> Cow<Term> {
        self.borrow_annot().get_base()
    }

    /// Get the type of this annotation
    #[inline]
    fn ty_id(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> Cow<TermId> {
        self.borrow_annot().get_ty_id(ctx)
    }

    /// Get the base type of this annotation
    #[inline]
    fn base_id(&self, ctx: &mut (impl ConsCtx + ?Sized)) -> Cow<TermId> {
        self.borrow_annot().get_base_id(ctx)
    }

    /// Attempt to coerce the type of this annotation in a given typing context.
    #[inline]
    fn coerce_ty(
        &self,
        target: &TermId,
        ctx: &mut (impl TyCtxMut + ?Sized),
    ) -> Result<Option<Annotation>, Error> {
        self.borrow_annot().get_coerce_ty(target, ctx)
    }
}

impl AnnotationLike for Annotation {
    fn borrow_annot(&self) -> AnnotationRef {
        match &*self.0 {
            Term::Refl(path) => AnnotationRef::Path(path),
            _term => AnnotationRef::Type(&self.0),
        }
    }
}

impl AnnotationLike for AnnotationRef<'_> {
    #[inline]
    fn borrow_annot(&self) -> AnnotationRef {
        self.clone()
    }
}